﻿using ManagementApi.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PmSoft;
using PmSoft.Exceptions;

namespace ManagementApi.Mvc.Filters
{
    /// <summary>
    /// 全局异常捕获
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        readonly ILogger logger;//采用内置日志记录
        readonly IWebHostEnvironment env;//环境变量

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env"></param>
        /// <param name="logger"></param>
        public GlobalExceptionFilter(IWebHostEnvironment env, ILogger<GlobalExceptionFilter> logger)
        {
            this.logger = logger;
            this.env = env;
        }

        /// <summary>
        /// 出现异常
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {

            if (context.Exception is BusinessException businessException)
            {
                context.Result = new JsonResult(ApiResult.Failure(businessException.Message));
                return;
            }
            else
            {
                logger.LogError(context.Exception, $"服务器异常，请求URL：{context.HttpContext.Request.GetDisplayUrl()}，异常信息：{context.Exception.Message}");
            }

            if (!env.IsDevelopment())
            {
                context.ExceptionHandled = true;
                context.Result = new JsonResult(ApiResult.Failure("服务器出现异常,请联系管理员"));
            }

        }
    }
}
